package com.koala.learn.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token 生成
 *
 * @author yantingrui
 * @date 2022/4/1   14:42
 */
public class Start {
    //密钥
    public static final String SECRET = "sdjhakdhajdklsl;o653632";
    //过期时间:秒
    public static final int EXPIRE = 8666;

    public static void main(String[] args) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, EXPIRE);
        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String sign = JWT.create().withHeader(map).withClaim("username", "Tom").withSubject("Test")
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
        System.out.println(sign);

    }

    /**
     *
     */
    @Test
    public void test43() {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJUZXN0IiwiZXhwIjoxNjQ4ODA1OTAyLCJ1c2VybmFtZSI6IlRvbSJ9.ltfa2Pb_iBjb3BiBv9jFuEOYcImMX26IfaMgp69M7UQ";
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT verify = verifier.verify(token);
        System.out.println(verify.getSubject());
    }
}
